<?php

namespace app\admin\controller\supplier;

use app\admin\model\Product;
use \app\admin\model\ProductLog;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use Symfony\Component\DependencyInjection\Argument\BoundArgument;
use think\App;
use app\admin\model\Rule;
use app\admin\model\Category;
use app\admin\model\Supplier;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="出货管理")
 */
class OrderShipment extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Shipment();


    }

    /**
     * @NodeAnotation(title="出货管理列表")
     */

    public function index()
    {

        $company_name = sysconfig('site','company_name');
        $company_address =  sysconfig('site','company_address');
        $company_receiver = sysconfig('site','company_receiver');

        $supplier_id = session('admin')['supplier_id'];

        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();

            
            if (!is_null($supplier_id)) {
                $where[] = [$this->model->getName() . '.supplier_id', '=', $supplier_id];
            }

            $count = $this->model
                ->withJoin(['supplier'], 'LEFT')
                ->where($where)
                ->count();

            $list = $this->model
                ->withJoin(['supplier'], 'LEFT')
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $list_arr = $list->toArray();


            $list = collection($list_arr)->map(function($v)use(&$list_arr,$company_name,$company_address,$company_receiver){
                $v['company_name'] = $company_name;
                $v['company_address'] = $company_address;
                $v['company_receiver'] = $company_receiver;
                return $v;
            })->toArray();

            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();

    }




    /**
     * @NodeAnotation(title="批量导出")
     */
    public function batch_export()
    {

        $supplier_id = session('admin')['supplier_id'];

        list($page, $limit, $where) = $this->buildTableParames();

        empty($where) && $this->error('数据不存在');

        if (!is_null($supplier_id)) {
            $where[] = [$this->model->getName() . '.supplier_id', '=', $supplier_id];
        }

        $list = $this->model
            ->withJoin(['category', 'supplier', 'rule', 'productMaps'], 'LEFT')
            ->field(['productMaps.item_number as item_number', 'category.name as category_name'])
            ->where($where)
            ->order($this->sort)
            ->select();

        $header = [
            'SKU',
            '工厂货号',
            '唯一码',
            '产品类别',
            '状态',
            'AI状态',
            '接单时间',
            '要求出货时间',
            '要求入库时间',
            '是否超时',
        ];
        $data= [];
        collection($list->toArray())->map(function($v,$k)use(&$data){
            $data[$k][] = $v['sku'];
            $data[$k][] = $v['item_number'];
            $data[$k][] = $v['unique_code'];
            $data[$k][] = $v['category_name'];
            $data[$k][] = $v['status'];
            $data[$k][] = $v['ai_status'];
            $data[$k][] = $v['accepted_time'];
            $data[$k][] = $v['delivery_at'];
            $data[$k][] = $v['give_time'];
            $data[$k][] = $v['is_overtime'] ==0 ? '超时':'未超时' ;
        });

//        dd($data);
        $title = '订单管理导出';

        exportExcel($title,$header,$data);
//        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }


    /**
     * @NodeAnotation(title="导入")
     */
    public function import()
    {
        $row = $this->request->get();
        if ($this->request->isAjax()) {

//            获取上传文件
            $file = $this->request->file('file');

//           读取上传文档 从第二行开始
            $data = Excel::import($file, 2);

            $category_arr = Category::field('id,name')->select()->toArray();
            $rule_arr = Rule::field('id,name')->select()->toArray();
            $supplier_arr = Supplier::field('id,name')->select()->toArray();


            $category_collection = collection($category_arr);
            $rule_collection = collection($rule_arr);
            $supplier_collection = collection($supplier_arr);

            $category_name_key = $category_collection->pluck('id', 'name')->toArray();
            $rule_name_key = $rule_collection->pluck('id', 'name')->toArray();
            $supplier_name_key = $supplier_collection->pluck('id', 'name')->toArray();

            $category_names = $category_collection->pluck('name');
            $rule_names = $rule_collection->pluck('name');
            $supplier_names = $supplier_collection->pluck('name');

            $category_names_arr = $category_names->toArray();
            $rule_names_arr = $rule_names->toArray();
            $supplier_names_arr = $supplier_names->toArray();

            $data_category = collection($data)->pluck('0');
            $data_rule = collection($data)->pluck('4');
            $data_supplier = collection($data)->pluck('7');
//            dd($category_ids_arr);

            $data_category->map(function ($item, $key) use ($category_names_arr) {
                $file_line_num = $key + 2;
                if (!in_array($item, $category_names_arr)) {
                    $this->error("您导入文件在第<{$file_line_num}>行 -统计分类- 列填写有误");
                }
            });

            $data_rule->map(function ($item, $key) use ($rule_names_arr) {
                $file_line_num = $key + 2;
                if (!in_array($item, $rule_names_arr)) {
                    $this->error("您导入文件在第<{$file_line_num}>行 -规则- 列填写有误");
                }
            });

            $data_supplier->map(function ($item, $key) use ($supplier_names_arr) {
                $file_line_num = $key + 2;
                if (!in_array($item, $supplier_names_arr)) {
                    $this->error("您导入文件在第<{$file_line_num}>行 -供应商- 列填写有误");
                }
            });

//            dd('到这里了 ');


//            总的统计  好用高效   没有统计到行
            /*            $category_ids = collection($data)->pluck('0')->merge($category_names)->unique()->count();
                        $rule_ids = collection($data)->pluck('4')->merge($rule_names)->unique()->count();
                        $supplier_ids = collection($data)->pluck('7')->merge($supplier_names)->unique()->count();

                        $count_default = $category_names->count() + $rule_names->count() + $supplier_names->count();
                        $count_new = $category_ids+$rule_ids+$supplier_ids;

                        if($count_default != $count_new){
                            $this->error('导入失败请检查导入文件内容是否含有未知名称');
                        }*/

            //          总的统计结束


//            dd($count_default,$count_new);


//            构建插入数据
            $time = time();
//            dd($category_name_key);
            $collect = collection($data)->map(function ($item) use ($time, $rule_name_key, $supplier_name_key, $category_name_key) {
                return [
                    'category_id' => $category_name_key[$item[0]],
                    'name' => $item[1],
                    'sku' => $item[2],
                    'item_number' => $item[3],
                    'rule_id' => $rule_name_key[$item[4]],
                    'cycle' => $item[5],
                    'is_auto' => ($item[6] == 'TRUE') ? 1 : 0,
                    'supplier_id' => $supplier_name_key[$item[7]],
                    'extension' => \GuzzleHttp\json_encode($item[8]),

                    'create_time' => $time,
                    'update_time' => $time
                ];
            });


            //规则，SKU，供应商 相同就更新
            $update_arr = [];
            $insert_collection = $collect->map(function ($item, $key) use (&$update_arr) {
                $where = [
                    ['rule_id', '=', $item['rule_id']],
                    ['sku', '=', $item['sku']],
                    ['supplier_id', '=', $item['supplier_id']],
                ];
                $count = $this->model->where($where)->find();

                if ($count) {
                    $item['id'] = $count->id;
                    $update_arr[] = $item;
                    return false;
                }
                return $item;
            });
            //过滤空数组
            $insert_data = array_filter($insert_collection->toArray());

            $update_status = $this->model->saveAll($update_arr);


//          可以分段插入设置$limit  insertAll($date,$limit)
            $insert_status = $this->model->insertAll($insert_data);

            ($insert_status and $update_status) ? $this->success('导入成功') : $this->error('导入失败');

        }

        $this->assign('row', $row);
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="详情")
     */
    public function detail($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');

        $list= Product::withJoin(['rule','productMaps'], 'LEFT')
            ->where('shipment_id', '=', $id)
            ->select()->toArray();

//        dd($list);
        $row = $list;

        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="拒单")
     */
    public function cancel($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');

        if ($this->request->isAjax()) {
            $admin = session("admin");
            $status = $this->request->post('status');
            if ($status != 'on') {
                $row->status = "拒单";
                $log = [
                    'product_id' => $row->id,
                    'remark' => '拒单',
                    'admin_id' => $admin['id'],
                    'type' => '拒单',
                ];
                $product_log = new ProductLog;
                $product_log->save($log);
            }


            try {
                $save = $row->save();
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $this->success('拒单成功');
        }


        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="接单")
     */
    public function get_order($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        $row->status = "已接单";

        $admin = session("admin");
        $log = [
            'product_id' => $row->id,
            'remark' => '接单',
            'admin_id' => $admin['id'],
            'type' => '接单',
        ];
        $product_log = new ProductLog;
        $product_log->save($log);

        try {
            $save = $row->save();
        } catch (\Exception $e) {
            $this->error('接单失败');
        }
        $this->success('接单成功');
    }

//    生成出货单
    public function batch_shipment()
    {
        $id_arr = $this->request->post('id');

        $where = [
            ['status', 'IN', ['已接单', '异常单', '返修中', '取消出货']],
            ['id', 'IN', $id_arr]
        ];

        try {
            $update = $this->model->where($where)->update(['status' => '已出货']);
        } catch (\Exception $e) {
            $this->error('生成出货单失败');
        }

        $update ? $this->success('生成出货单成功') : $this->error('生成出货单失败');
    }

//    批量接单
    public function batch_take_order()
    {
        $id_arr = $this->request->post('id');

        $where = [
            ['status', 'IN', ['已派单', '已拒单', '已收货']],
            ['id', 'IN', $id_arr]
        ];

        try {
            $update = $this->model->where($where)->update(['status' => '已接单']);
        } catch (\Exception $e) {
            $this->error('批量接单失败');
        }

        $update ? $this->success('批量接单成功') : $this->error('批量接单失败');


    }

//    批量拒单
    public function batch_discard_order()
    {
        $id_arr = $this->request->post('id');

        $where = [
            ['status', 'IN', ['已接单', '已派单', '已收货', '取消出货']],
            ['id', 'IN', $id_arr]
        ];

        try {
            $update = $this->model->where($where)->update(['status' => '已拒单']);
        } catch (\Exception $e) {
            $this->error('批量拒单失败');
        }

        $update ? $this->success('批量拒单成功') : $this->error('批量拒单失败');
    }

}